package cn.cvs.controller;

import cn.cvs.entity.SysRole;
import cn.cvs.entity.SysUser;
import cn.cvs.service.sysRole.SysRoleService;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/user")
public class SysUserController extends BaseController{
	private Logger logger = Logger.getLogger(SysUserController.class);
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysRoleService sysRoleService;



	/**
	 * 查询用户列表
	 * @param model
	 * @param queryRealName
	 * @param queryRoleId
	 * @param pageIndex
	 * @return
	 */
	@RequestMapping(value="/list")
	public String getUserList(Model model
			,@RequestParam(value="queryRealName",required=false) String queryRealName
			,@RequestParam(value="queryRoleId",required=false) Integer queryRoleId
			,@RequestParam(value="pageIndex",required=false, defaultValue = "1") Integer pageIndex){
		List<SysUser> userList = null;
		//设置页面容量
		int pageSize = Constants.pageSize;
		try{
			//总数量（表）
			int totalCount	= sysUserService.getUserCount(queryRealName,queryRoleId);
			//总页数
			PageSupport pages=new PageSupport();
			pages.setCurrentPageNo(pageIndex);
			pages.setPageSize(pageSize);
			pages.setTotalCount(totalCount);
			int totalPageCount = pages.getTotalPageCount();
			//控制首页和尾页
			if(pageIndex > totalPageCount){
				pageIndex = totalPageCount;
			}
			userList = sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
			model.addAttribute("userList", userList);
			List<SysRole> roleList = null;
			roleList = sysRoleService.getRoleList();
			model.addAttribute("roleList", roleList);
			model.addAttribute("queryRealName", queryRealName);
			model.addAttribute("queryRoleId", queryRoleId);
			model.addAttribute("totalPageCount", totalPageCount);
			model.addAttribute("totalCount", totalCount);
			model.addAttribute("currentPageNo", pageIndex);
		}catch(Exception e){
			e.printStackTrace();
			return "redirect:/sys/toSysError";
		}
		return "sysUser/list";
	}


	/**
	 * 跳转到添加用户页面
	 * @return
	 */
	@GetMapping("/toAdd")
	public String addUser(){
		return "sysUser/add";
	}

	/**
	 * 多文件上传
	 * @param sysUser
	 * @param session
	 * @param request
	 * @param attachs
	 * @return
	 */
	/*@PostMapping(value="/add")
	public String addUserSave(SysUser sysUser,HttpSession session,HttpServletRequest request,
							  @RequestParam(value ="idPic", required = false) MultipartFile[] attachs){
		String idPicPath = null;
		String workPicPath = null;
		String errorInfo = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		logger.info("uploadFile path ============== > "+path);
		for(int i = 0;i < attachs.length ;i++){
			MultipartFile attach = attachs[i];
			if(!attach.isEmpty()){
				if(i == 0){
					errorInfo = "uploadFileError";
				}else if(i == 1){
					errorInfo = "uploadWpError";
				}
				String oldFileName = attach.getOriginalFilename();//原文件名
				logger.info("uploadFile oldFileName ============== > "+oldFileName);
				String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
				logger.debug("uploadFile prefix============> " + prefix);
				int filesize = 500000;
				logger.debug("uploadFile size============> " + attach.getSize());
				if(attach.getSize() >  filesize){//上传大小不得超过 500k
					request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
					flag = false;
				}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
					String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
					logger.debug("new fileName======== " + attach.getName());
					File targetFile = new File(path, fileName);
					if(!targetFile.exists()){
						targetFile.mkdirs();
					}
					//保存
					try {
						attach.transferTo(targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						request.setAttribute(errorInfo, " * 上传失败！");
						flag = false;
					}
					if(i == 0){
						idPicPath = path+File.separator+fileName;
					}else if(i == 1){
						workPicPath = path+File.separator+fileName;
					}
					logger.debug("idPicPath: " + idPicPath);
					logger.debug("workPicPath: " + workPicPath);

				}else{
					request.setAttribute(errorInfo, " * 上传图片格式不正确");
					flag = false;
				}
			}
		}
		if(flag){
			sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
			sysUser.setIdPicPath(idPicPath);
			sysUser.setWorkPicPath(workPicPath);
			if(sysUserService.add(sysUser)){
				return "redirect:/sys/user/list";
			}
		}
		return "sysUser/add";
	}*/

	/**
	 * 多文件上传
	 */
	@PostMapping("/add")
	public String addUserSave(SysUser sysUser,HttpSession session,HttpServletRequest request
			,@RequestParam(value ="idPic", required = false) MultipartFile idPic
			,@RequestParam(value ="workPic", required = false) MultipartFile workPic){
		String idPicPath = null;
		String workPicPath = null;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		logger.info("uploadFile path ============== > "+path);

		//判断文件是否为空(证件照)
		if(!idPic.isEmpty()){
			String oldFileName = idPic.getOriginalFilename();//原文件名
			logger.info("uploadFile oldFileName ============== > "+oldFileName);
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
			logger.debug("uploadFile prefix============> " + prefix);
			int filesize = 500000;
			logger.debug("uploadFile size============> " + idPic.getSize());
			if(idPic.getSize() >  filesize){//上传大小不得超过 500k
				request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
				return "sysUser/add";
			}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
				String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
				logger.debug("new fileName======== " + idPic.getName());
				File targetFile = new File(path, fileName);
				if(!targetFile.exists()){
					targetFile.mkdirs();
				}
				//保存
				try {
					idPic.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("uploadFileError", " * 上传失败！");
					return "sysUser/add";
				}
				idPicPath = path+File.separator+fileName;
			}else{
				request.setAttribute("uploadFileError", " * 上传图片格式不正确");
				return "sysUser/add";
			}
		}

		//判断文件是否为空(工作证照)
		if(!workPic.isEmpty()){
			String oldFileName = workPic.getOriginalFilename();//原文件名
			logger.info("uploadFile oldFileName ============== > "+oldFileName);
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
			logger.debug("uploadFile prefix============> " + prefix);
			int filesize = 500000;
			logger.debug("uploadFile size============> " + workPic.getSize());
			if(workPic.getSize() >  filesize){//上传大小不得超过 500k
				request.setAttribute("uploadWpError", " * 上传大小不得超过 500k");
				return "useradd";
			}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
				String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
				logger.debug("new fileName======== " + workPic.getName());
				File targetFile = new File(path, fileName);
				if(!targetFile.exists()){
					targetFile.mkdirs();
				}
				//保存
				try {
					workPic.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("uploadWpError", " * 上传失败！");
					return "sysUser/add";
				}
				workPicPath = path+File.separator+fileName;
			}else{
				request.setAttribute("uploadWpError", " * 上传图片格式不正确");
				return "sysUser/add";
			}
		}

		try{
			sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
			sysUser.setIdPicPath(idPicPath);
			sysUser.setWorkPicPath(workPicPath);
			if(sysUserService.add(sysUser)){
				return "redirect:/sys/user/list";
			}
		}catch (Exception e){
			e.printStackTrace();
			logger.error("保存用户信息失败");
		}
		return "sysUser/add";
	}


	/**
	 * 跳转到修改用户页面
	 * @param uid
	 * @param model
	 * @return
	 */
	@GetMapping("/toUpdate")
	public String getUserById(@RequestParam Integer uid,Model model)throws Exception {
		logger.debug("跳转到修改用户信息页面");
		SysUser sysUser = sysUserService.getUserById(uid);
		model.addAttribute(sysUser);
		return "sysUser/update";
	}

	/**
	 * 修改用户信息
	 * @param sysUser
	 * @param session
	 * @return
	 */
	@PostMapping("/update")
	public String modifyUserSave(SysUser sysUser,HttpSession session)throws Exception {
		logger.debug("修改用户信息");
		sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
		if(sysUserService.update(sysUser)){
			return "redirect:/sys/user/list";
		}
		return "sysUser/update";
	}

	/**
	 * 查询用户详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/view/{id}")
	public String view(@PathVariable Integer id,Model model)throws Exception {
		logger.debug("根据id查询用户详情"+id);
		SysUser sysUser = sysUserService.getUserById(id);
		model.addAttribute(sysUser);
		return "sysUser/view";
	}

	/**
	 * 查询用户详情，返回JSON
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("/{id}/view")
	public Object view(@PathVariable Integer id)throws Exception {
		logger.debug("根据id查询用户详情id:" + id);
		SysUser sysUser = null;
		sysUser = sysUserService.getUserById(id);
		logger.debug("查询到用户信息：" + sysUser);
		return sysUser;
	}


	/**
	 * 验证用户编号是否已存在
	 * @param account
	 * @return
	 */
	@ResponseBody
	@GetMapping("/userExist")
	public Object userExist(@RequestParam(required = true) String account)throws Exception {
		logger.debug("验证用户名account="+account + "的用户是否存在");
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try{
			// 角色编号不可为空
			if(account == null || "".equals(account.trim())){
				resultMap.put("exist", -1);
				resultMap.put("msg", "用户名不可以为空");
			}else {
				SysUser sysUser = sysUserService.getByAccount(account);
				if(null != sysUser) {
					resultMap.put("exist", 1);
				}else {
					resultMap.put("exist", 0);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return JSONArray.toJSONString(resultMap);
	}

	/**
	 * 跳转到修改密码页面
	 * @param session
	 * @return
	 */
	@GetMapping("/toUpdatePwd")
	public String toUpdatePwd(HttpSession session)throws Exception {
		if(session.getAttribute(Constants.USER_SESSION) == null){
			return "redirect:/toLogin";
		}
		return "sysUser/updatePassword";
	}

	/**
	 * 修改密码
	 * @param oldPassword
	 * @param session
	 * @return
	 */
	@ResponseBody
	@PostMapping("/checkOldPwd")
	public Object checkOldPwd(@RequestParam String oldPassword,HttpSession session)throws Exception {
		logger.debug("验证原密码 oldPassword ===================== "+oldPassword);
		HashMap<String, String> resultMap = new HashMap<String, String>();
		try{
			if(null == session.getAttribute(Constants.USER_SESSION) ){//session过期
				resultMap.put("result", "sessionerror");
			}else if(StringUtils.isNullOrEmpty(oldPassword)){//旧密码输入为空
				resultMap.put("result", "error");
			}else{
				String sessionPwd = ((SysUser)session.getAttribute(Constants.USER_SESSION)).getPassword();
				if(oldPassword.equals(sessionPwd)){
					resultMap.put("result", "true");
				}else{//旧密码输入不正确
					resultMap.put("result", "false");
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return JSONArray.toJSONString(resultMap);
	}
	/**
	 * 修改密码
	 * @param newPassword
	 * @param session
	 * @return
	 */
	@PostMapping(value="/savePassword")
	public String savePassword(@RequestParam(value="newPassword") String newPassword
			,HttpSession session,HttpServletRequest request)throws Exception {
		boolean flag = false;
		SysUser loginUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
		if(loginUser != null && !StringUtils.isNullOrEmpty(newPassword)){
			flag = sysUserService.updatePwd(loginUser.getId(),newPassword);
			if(flag){
				request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
				session.removeAttribute(Constants.USER_SESSION);//session注销
				return "login";
			}else{
				request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
			}
		}else{
			request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
		}
		return "sysUser/updatePassword";
	}

	/**
	 * 根据id异步删除用户信息
	 * @param id
	 * @return
	 */
	@DeleteMapping("/del/{id}")
	@ResponseBody
	public Object del(@PathVariable(value = "id",required = true) Integer id) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		try {
			if(sysUserService.deleteById(id)){
				resultMap.put("delResult", "true");
			}else{
				resultMap.put("delResult", "false");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JSONArray.toJSONString(resultMap);
	}


	/**
	 * 一个抛出异常的接口
	 * @return
	 */
	@RequestMapping("/exLogin")
	public String exLogin() throws Exception {
		logger.debug("一个抛出异常的接口");
		//调用service方法，进行用户匹配
		SysRole sysRole = sysRoleService.getById(100);
		if(null == sysRole){//登录失败
			throw new Exception("系统异常！");
		}
		return "redirect:/toMain";
	}

}
